﻿using DevExpress.XtraEditors;
using EFERP;
using HRM.DICTIONARY.DAL;
using System;
using System.Linq;
using System.Windows.Forms;

namespace HRM.DICTIONARY.UI
{
    public partial class xfrmContractAdd : XtraForm
    {
        private hrm_contract _obj;
        private hrm_employee _objEmployee;
        private readonly ICommon<hrm_contract> _exeDic;
        private readonly ICommon<hrm_employee> _exeDicEmployee;
        private CloseOrNew _closeNew = CloseOrNew.Close;

        public xfrmContractAdd(ICommon<hrm_contract> exeDic)
        {
            InitializeComponent();
            this._exeDicEmployee = new Common<hrm_employee>(StaticVariable.ERPEn);
            this._exeDic = exeDic;
            this._exeDic.myAction = Actions.Insert;
            this._obj = new hrm_contract();
            SetDataIntoGridLookup();
            SetDataIntoUI();
        }

        public xfrmContractAdd(hrm_contract currObj, ICommon<hrm_contract> exeDic)
        {
            InitializeComponent();
            this._exeDicEmployee = new Common<hrm_employee>(StaticVariable.ERPEn);
            this._exeDic = exeDic;
            this._exeDic.myAction = Actions.Update;
            this._obj = currObj;
            SetDataIntoGridLookup();
            SetDataIntoUI();
        }

        private void xfrmContractAdd_FormClosing(object sender, FormClosingEventArgs e)
        {
            TotalClose();
        }

        private void SetDataIntoUI()
        {
            if (_obj == null)
                return;
            switch (_exeDic.myAction)
            {
                case Actions.Update:
                    txtContractCode.Text = _obj.contractcode;
                    this.glkEmployeeCode.Properties.ReadOnly = true;
                    this.glkEmployeeCode.EditValue = _obj.employeecode;
                    this.glkSignerCode.EditValue = _obj.signer;
                    if (_obj.contracttype != null) this.cboContractType.SelectedIndex = (int)_obj.contracttype;
                    this.cboContractTime.Text = _obj.contracttime;
                    if (_obj.signdate != null) this.dtSignDate.DateTime = (DateTime)_obj.signdate;
                    if (_obj.fromdate != null) this.dtFromDate.DateTime = (DateTime)_obj.fromdate;
                    if (_obj.todate != null) this.dtToDate.DateTime = (DateTime)_obj.todate;
                    this.calBasicSalary.EditValue = _obj.basicsalary;
                    this.cboPayForm.Text = _obj.payform;
                    this.txtPayDate.Text = _obj.paydate;
                    this.txtAllowance.Text = _obj.allowance;
                    this.txtInsurance.Text = _obj.insurance;
                    this.txtWorkTime.Text = _obj.worktime;
                    this.calCompensation.EditValue = _obj.compensation;
                    this.txtSigner.Text = _obj.signer;
                    this.txtSignerPosition.Text = _obj.signerposition;
                    this.txtSignerNationality.Text = _obj.signernationality;
                    this.txtCompany.Text = _obj.company;
                    this.txtAddress.Text = _obj.address;
                    this.txtTel.Text = _obj.tel;
                    this.txtCreatePlace.Text = _obj.createplace;
                    this.txtSubject.Text = _obj.subject;
                    this.txtDescription.Text = _obj.description;

                    btnLuuDong.Visible = true;
                    btnThoat.Visible = true;
                    btnLuuThem.Visible = false;
                    break;

                case Actions.Insert:
                    _obj = new hrm_contract();
                    this.glkEmployeeCode.Properties.ReadOnly = false;
                    txtContractCode.Text = _exeDic.NewID("HD");
                    this.cboContractType.SelectedIndex = 0;
                    this.cboContractTime.Text = "";
                    this.dtSignDate.DateTime = DateTime.Today;
                    this.dtFromDate.DateTime = DateTime.Today;
                    this.dtToDate.DateTime = DateTime.Today.AddYears(3);
                    this.calBasicSalary.EditValue = 0;
                    this.cboPayForm.Text = "";
                    this.txtPayDate.Text = "";
                    this.txtAllowance.Text = "";
                    this.txtInsurance.Text = "";
                    this.txtWorkTime.Text = "";
                    this.calCompensation.EditValue = 0;
                    this.txtSigner.Text = "";
                    this.txtSignerPosition.Text = "";
                    this.txtSignerNationality.Text = "";
                    this.txtCompany.Text = "";
                    this.txtAddress.Text = "";
                    this.txtTel.Text = "";
                    this.txtCreatePlace.Text = "";
                    this.txtSubject.Text = "";
                    this.txtDescription.Text = "";

                    btnLuuDong.Visible = true;
                    btnThoat.Visible = true;
                    btnLuuThem.Visible = true;
                    break;

                case Actions.InsertMultiple:
                    _obj = new hrm_contract();
                    this.glkEmployeeCode.Properties.ReadOnly = false;
                    txtContractCode.Text = _exeDic.NewID("HD");
                    this.glkEmployeeCode.EditValue = "";
                    this.cboContractType.SelectedIndex = 0;
                    this.cboContractTime.Text = "";
                    this.dtSignDate.DateTime = DateTime.Today;
                    this.dtFromDate.DateTime = DateTime.Today;
                    this.dtToDate.DateTime = DateTime.Today.AddYears(3);
                    this.calBasicSalary.EditValue = 0;
                    this.cboPayForm.Text = "";
                    this.txtPayDate.Text = "";
                    this.txtAllowance.Text = "";
                    this.txtInsurance.Text = "";
                    this.txtWorkTime.Text = "";
                    this.calCompensation.EditValue = 0;
                    this.txtSigner.Text = "";
                    this.txtSignerPosition.Text = "";
                    this.txtSignerNationality.Text = "";
                    this.txtCompany.Text = "";
                    this.txtAddress.Text = "";
                    this.txtTel.Text = "";
                    this.txtCreatePlace.Text = "";
                    this.txtSubject.Text = "";
                    this.txtDescription.Text = "";

                    btnLuuDong.Visible = true;
                    btnThoat.Visible = true;
                    btnLuuThem.Visible = true;
                    break;
            }
        }

        private bool SetUIIntoData()
        {
            if (txtContractCode.Text == "" || txtContractName.Text == "")
            {
                MessageBox.Show(@"Vui lòng không để trống thông tin hợp đồng");
                return false;
            }
            if (this.glkEmployeeCode.EditValue != null)
            {
                _obj.employeecode = this.glkEmployeeCode.EditValue.ToString();
            }
            else
            {
                XtraMessageBox.Show("Vui lòng chọn nhân viên cần tạo hợp đồng!");
                return false;
            }
            _obj.contractcode = txtContractCode.Text;
            _obj.contracttype = this.cboContractType.SelectedIndex;
            _obj.contracttime = this.cboContractTime.Text;
            _obj.signdate = this.dtSignDate.DateTime;
            _obj.fromdate = this.dtFromDate.DateTime;
            _obj.todate = this.dtToDate.DateTime;
            _obj.basicsalary = decimal.Parse(this.calBasicSalary.EditValue.ToString());
            _obj.payform = this.cboPayForm.Text;
            _obj.paydate = this.txtPayDate.Text;
            _obj.allowance = this.txtAllowance.Text;
            _obj.insurance = this.txtInsurance.Text;
            _obj.worktime = this.txtWorkTime.Text;
            _obj.compensation = decimal.Parse(this.calCompensation.EditValue.ToString());
            _obj.signer = this.txtSigner.Text;
            _obj.signerposition = this.txtSignerPosition.Text;
            _obj.signernationality = this.txtSignerNationality.Text;
            _obj.company = this.txtCompany.Text;
            _obj.address = this.txtAddress.Text;
            _obj.tel = this.txtTel.Text;
            _obj.createplace = this.txtCreatePlace.Text;
            _obj.subject = this.txtSubject.Text;
            _obj.description = this.txtDescription.Text;

            //---------------Employee--------------------------------------------------------
            _objEmployee = _exeDicEmployee.GetById(_obj.employeecode);
            if (_objEmployee != null)
            {
                _objEmployee.contractcode = txtContractCode.Text;
                _objEmployee.contractfromdate = this.dtFromDate.DateTime;
                _objEmployee.contractsigndate = this.dtSignDate.DateTime;
                _objEmployee.contracttodate = this.dtToDate.DateTime;
                _objEmployee.contracttype = cboContractType.Text;
            }
            return true;
        }

        //Add them if we have to combine the other tables to get data
        private bool SetDataIntoGridLookup()
        {
            bool kq = SetDataSysEmployeeIntoGridLookup();
            if (kq)
                kq = SetDataSysSignerIntoGridLookup();
            if (kq) return true;
            XtraMessageBox.Show(_exeDicEmployee.ErrMsg, "Cảnh Báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return false;
        }

        private bool SetDataSysEmployeeIntoGridLookup()
        {
            bool kq = _exeDicEmployee.AddGridLookupEdit(glkEmployeeCode, "employeecode", "employeecode");
            if (!kq) return false; return true;
        }

        private bool SetDataSysSignerIntoGridLookup()
        {
            bool kq = _exeDicEmployee.AddGridLookupEdit(glkSignerCode, "employeecode", "employeecode");
            if (!kq) return false;
            return true;
        }

        private bool CheckEmployeeContract(string employeecode)
        {
            hrm_employee objEmployee = _exeDicEmployee.GetById(employeecode);
            if (objEmployee == null) return false;
            if (objEmployee.contractcode == "") return true;
            return false;
        }

        private void TotalControl()
        {
            bool kq;
            switch (_exeDic.myAction)
            {
                case Actions.Insert:
                    kq = SetUIIntoData();
                    if (kq)
                    {
                        kq = CheckEmployeeContract(_obj.employeecode);
                        if (kq)
                        {
                            kq = _exeDic.InsertOnGridView(_obj);
                            if (kq)
                            {
                                kq = _exeDicEmployee.Update(_objEmployee);
                                if (kq)
                                {
                                    this.DialogResult = DialogResult.OK;
                                    _exeDic.myAction = Actions.Insert;
                                    this.Close();
                                }
                            }
                            else
                            {
                                MessageBox.Show(@"Lỗi thêm dữ liệu vào hệ thống");
                            }
                        }
                        else
                        {
                            MessageBox.Show(@"Nhân viên này đã có hợp đồng!");
                        }
                    }
                    break;

                case Actions.Update:kq = SetUIIntoData();
                    if (kq)
                    {
                        kq = _exeDic.UpdateOnGridView(_obj);
                        if (kq)
                        {
                            kq = _exeDicEmployee.Update(_objEmployee);
                            if (kq)
                            {
                                this.DialogResult = DialogResult.OK;
                                _exeDic.myAction = Actions.Update;
                                this.Close();
                            }
                        }
                        else
                        {
                            _exeDic.ValueOfGridViewRow = null;
                            MessageBox.Show(@"Lỗi cập nhật dữ liệu vào hệ thống");
                        }
                    }
                    break;

                case Actions.InsertMultiple:
                    kq = SetUIIntoData();
                    if (kq)
                    {
                        kq = CheckEmployeeContract(_obj.employeecode);
                        if (kq)
                        {
                            kq = _exeDic.InsertOnGridView(_obj);
                            if (kq)
                            {
                                kq = _exeDicEmployee.Update(_objEmployee);
                                if (kq)
                                {
                                    _exeDic.myAction = Actions.InsertMultiple;
                                    SetDataIntoUI();
                                    this.DialogResult = DialogResult.OK;
                                    if (_closeNew == CloseOrNew.Close)
                                        this.Close();
                                    else
                                        _closeNew = CloseOrNew.New;
                                }
                            }
                            else
                            {
                                MessageBox.Show(@"Lỗi thêm dữ liệu vào hệ thống");
                            }
                        }
                        else
                        {
                            MessageBox.Show(@"Nhân viên này đã có hợp đồng!");
                        }
                    }
                    break;
            }
        }

        private void TotalClose()
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            TotalClose();
        }

        private void btnLuuDong_Click(object sender, EventArgs e)
        {
            _closeNew = CloseOrNew.Close;
            TotalControl();
        }

        private void btnLuuThem_Click(object sender, EventArgs e)
        {
            _exeDic.myAction = Actions.InsertMultiple;
            _closeNew = CloseOrNew.New;
            TotalControl();
        }

        private void cboContractTime_EditValueChanged(object sender, EventArgs e)
        {
            if (this.cboContractTime.SelectedIndex == 0)
            {
                this.dtToDate.DateTime = this.dtFromDate.DateTime.AddMonths(2);
            }
            else if (this.cboContractTime.SelectedIndex == 1)
            {
                this.dtToDate.DateTime = this.dtFromDate.DateTime.AddMonths(3);
            }
            else if (this.cboContractTime.SelectedIndex == 2)
            {
                this.dtToDate.DateTime = this.dtFromDate.DateTime.AddMonths(6);
            }
            else if (this.cboContractTime.SelectedIndex == 3)
            {
                this.dtToDate.DateTime = this.dtFromDate.DateTime.AddMonths(9);
            }
            else if (this.cboContractTime.SelectedIndex == 4)
            {
                this.dtToDate.DateTime = this.dtFromDate.DateTime.AddYears(1);
            }
            else if (this.cboContractTime.SelectedIndex == 5)
            {
                this.dtToDate.DateTime = this.dtFromDate.DateTime.AddYears(2);
            }
            else if (this.cboContractTime.SelectedIndex == 6)
            {
                this.dtToDate.DateTime = this.dtFromDate.DateTime.AddYears(3);
            }
        }

        private void cboContractType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cboContractType.SelectedIndex == 1)
            {
                this.lcContractTime.Visible = false;
                this.cboContractTime.Visible = false;
                this.lcToDate.Visible = false;
                this.dtToDate.Visible = false;
            }
            else
            {
                this.lcContractTime.Visible = true;
                this.cboContractTime.Visible = true;
                this.lcToDate.Visible = true;
                this.dtToDate.Visible = true;
            }
        }

        private void glkEmployeeCode_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                string employeeid = glkEmployeeCode.EditValue.ToString();
                hrm_employee objEmployee = _exeDicEmployee.GetById(employeeid);
                if (objEmployee != null)
                {
                    this.txtEmployeeName.Text = objEmployee.firstname + @" " + objEmployee.lastname;
                    if (objEmployee.birthday != null) this.xdeBirthday.DateTime = (DateTime)objEmployee.birthday;

                    if (objEmployee.dic_position != null) this.txtPosition.Text = objEmployee.dic_position.positionname;
                    if (objEmployee.dic_nationality != null)
                        this.txtNationality1.Text = objEmployee.dic_nationality.nationalityname;
                    this.txtIDCard.Text = objEmployee.idcard;
                    if (objEmployee.idcarddate != null) this.dtIDCardDate.DateTime = (DateTime)objEmployee.idcarddate;
                    this.txtIDCardPlace.Text = objEmployee.idcardplace;
                    if (objEmployee.hrm_branch != null && objEmployee.hrm_department != null)
                        this.txtDepartment.Text = objEmployee.hrm_branch.branchname + @" - " + objEmployee.hrm_department.departmentname;
                    this.calBasicSalary.EditValue = objEmployee.basicsalary;

                    if (objEmployee.hrm_employee_allowance != null)
                        foreach (hrm_employee_allowance objAllowance in objEmployee.hrm_employee_allowance.ToList().Where(objAllowance => objAllowance.dic_allowance != null))
                        {
                            this.txtAllowance.Text = this.txtAllowance.Text + objAllowance.dic_allowance.allowancename + @"; ";
                        }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void glkSignerCode_EditValueChanged(object sender, EventArgs e)
        {
            string employeeid = glkSignerCode.EditValue.ToString();
            hrm_employee objEmployee = _exeDicEmployee.GetById(employeeid);

            if (objEmployee != null)
            {
                this.txtSigner.Text = objEmployee.firstname + @" " + objEmployee.lastname;
                if (objEmployee.dic_position != null)
                    this.txtSignerPosition.Text = objEmployee.dic_position.positionname;
                if (objEmployee.dic_nationality != null)
                    this.txtSignerNationality.Text = objEmployee.dic_nationality.nationalityname;
            }
        }
    }
}